<template>
	<view>
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<u-sticky class="u-sticky">
			<view class="padding-sm flex light " style="background-color: white;">
				<u-search v-model="barCode" :show-action="false" @search="confirm()" placeholder="输入拣货单号搜索" ></u-search>
			</view>
			<view class="grid margin-bottom text-center col-5">
				<view class="padding-top-sm padding-bottom-sm text-bold" v-for="(item,indexs) in topData" :key="indexs" :style="{'width': item.width}">
					<view v-if="item.name === 'checkbox'"><checkbox @click="checkAllChange" :checked="checkAll"></checkbox></view>
					<view v-else>{{ item.name }}</view>
				</view>
				
			</view>
			
		</u-sticky>		
		<scroll-view scroll-y="true" class="scroll-view-class">
			<!-- :style="{ height: computedScrollViewHeight }" -->
			<view class="scroll-content flex" ref="scrollContent" style="
			   display: flex;
			   flex-direction: column;
			   justify-content: space-between;">
			   <checkbox-group>
					<view class="grid margin-bottom text-center col-5" v-for="(item,indexs) in list" :key="item.id">
						<view class="" style="width: 10%;">
							<view>{{ indexs+1 }}</view>
						</view>
						<view class="" style="width: 40%;">
							<view>{{ item.djno }}</view>
						</view>
						<view class="" style="width: 25%;">
							<view>{{ item.fperson }}</view>
						</view>
						<view class="" style="width: 15%;">
							<view>{{ item.fqty }}</view>
						</view>
						<view class="" style="width: 10%;">
							<view><checkbox @click="checkItem(item,indexs)" :checked="item.checked"></checkbox></view>
						</view>
					</view>
				</checkbox-group>
				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 80vh;"></u-empty>
			</view>
		</scroll-view>
		
		<!-- v-if="flag" -->
		<view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="handleSubmit" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view >确认出库</view>
						</view>
					</u-button>
					
				</movable-view>
			</movable-area>
		</view>
		<view class="footer" >
			<view style="border-bottom:1px solid #eee ;padding: 20rpx;" class="flex justify-around">
				<view style="display: flex;align-items: center;" >
					<view style="width: 170rpx;">拣货单合计：</view>
					<view style="flex: 1;" class=" text-xl"> {{ jhSumQty || "0"  }}</view>
				</view>
				<view style="display: flex;align-items: center;" >
					<view style="width: 200rpx;">确认出库合计：</view>
					<view style="flex: 1;" class=" text-xl"> {{ ckSumQty || "0"  }}</view>
				</view>
		
			</view>
		</view>
	</view>
</template>
<script>
	import {
		hasPermission
	} from '@/common/fire.js'
	import dictLabel from "@/components/dictLabel.vue";
	export default {
		components: {
			dictLabel,
		},
		data() {
			return {
				x: 650, //x坐标
				y: 650, //y坐标
				companySelectList:[],
				show: false,
				smshow: false,
				focus: false,
				barCode: "",
				remarks: '',
				czData: {},
				show2: false,
				type: 'text',
				startTime: false, //控制日期显示
				endTime: false, //控制日期显示
				show: false,
				inputStyle: {
					fontSize: '34rpx'
				},
				filterIcon: "/static/image/filter.png",
				keyword: "",
				background: {
					backgroundColor: '#3E97B0',
				},
				list: [],
				itemContent: {},
				query: {
					pageNo: 1,
					pageSize: 5,
					// jhStatus:[0,1]
					// orderBy: "a.create_date desc",
				},
				loadStatus: "loadmore",
				triggered: false,
				flag: false,
				scrollViewHeight: 0,
				headerHeight: 0,
				jhStatusInName: '',
				type:'',
				// '序号','出库订单','联系人','数量','checkbox'
				topData: [{
					name: '序号',
					width: '10%'
				},{
					name: '出库订单',
					width: '40%'
				},{
					name: '联系人',
					width: '25%'
				},{
					name: '数量',
					width: '15%'
				},{
					name: 'checkbox',
					width: '10%'
				}],
				ckSumQty: 0,//当list 里面的数据发生变化
			};
		},
		onShow() {
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			
			
			this.query.companyCode = this.vuex_company.companyCode || '';
			this.query['company.companyName']= this.vuex_company.companyName || '';
			this.query.pageNo = 1;
			// 
			// this.query.pageNo = 1;
			// this.loadData();
			// this.$u.api.ktnw.companyTreeData().then(res => {
			// 	this.companySelectList = res;
			// });
			
		},
		onLoad() {
			// this.loadData()
		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		mounted() {

			this.calculateScrollViewHeight();
		},
		computed: {
			computedScrollViewHeight() {
				return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
			},
			// 计算list 里面的fhQty总和
			jhSumQty() {
				let sum = 0;
				this.list.forEach(item => {
					sum += item.fqty;
				});
				console.log('jhSumQty', sum);
				return sum;
			},
			checkAll() {
				let checked = false;
				if (this.list.length > 0 && this.list.every(item => item.checked)) {
					checked = true;
				} else {
					checked = false;
				}
				console.log('checkAll', checked);
				return checked;
			},
			


		},
		// 监听list 里面的数据变化
		watch: {
			list: {
				handler(newVal, oldVal) {
					this.ckSumQty = newVal.reduce((total, item) => {
						// console.log(item.fqty,'item.fqty')	
						if (item.checked) {
							total += Number(item.fqty);
						}
						return total;
					}, 0);
				},
				deep: true,
			},
		},
		methods: {
			handleSubmit() {
				let _that = this
				const selIds = this.list.filter(item => item.checked).map(item => item.djno).join(',');
				this.$u.api.ktnw.rdOrderConfirm({
					selIds: selIds,
				}).then(res => {
					if (res.result == 'true') {
						// this.$u.toast(res.message);
						// setTimeout(()=>{
						// 	uni.navigateBack({
						// 		delta: 1
						// 	})
						// },500)
						const msg = res.message.replace(/posfull:<br>/g, '')
						uni.showModal({
							title: '提示',
							content: msg,
							confirmColor: '#F54E40',
							success: (res) => {
								if (!res.confirm) {
									return false;
								}
								this.list = [];
								uni.$off('xwscan', this.BroadcastScanningToObtainData)
								setTimeout(()=>{
									uni.$on('xwscan', this.BroadcastScanningToObtainData)
								},10)
							}
						})
					}else{
						this.$refs.jsError.showError('',res.message,'error');
					}
				});
			},
			checkItem(item,index){
				const newItem = {...this.list[index], checked: !this.list[index].checked};
				this.list.splice(index, 1, newItem);
			},
			checkAllChange(){
				this.list = this.list.map(item => ({...item, checked: !this.checkAll}));
				this.$forceUpdate();

			},
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500)
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code
				
				
				//判断条形码长度是否大于3
				if(barcode.length > 3){
					//去除换行符
					let newString = barcode.replace('\n;', '');
					
					this.barCode = newString;
					this.confirm()
				}
			},
			async confirm() {
				let _this = this;
				
				if (this.barCode) {
					// this.query.djno = this.barCode
					// this.loadData()
					await this.$u.api.ktnw.findDckList({
						pickCode :this.barCode
					}).then((res) => {
						console.log(res,'res=====')
						if (res.result == "true") {
							_this.sendMp3('cg');
							uni.$off('xwscan', this.BroadcastScanningToObtainData)
							// uni.navigateTo({
							// 	url: '/pages/ktnw/ckdd/form?djno=' + res.list[0].djno,
							// })
							this.list = res.data;
							this.list.forEach(item=>{
								item.checked = false;
							})
							
						}else{
							_this.sendMp3('sb');
							_this.$refs.jsError.showError("", "请扫描正确的出库单号！", "warn");
						}
					});
					
					setTimeout(()=>{
						this.barCode = ''
					},500)
					
					
				} else {
					_this.sendMp3('sb');
					// this.$u.toast("任务单号不能为空!");
					_this.$refs.jsError.showError("", "出库单号不能为空", "warn");
				}
			},
			search() {
				let _that = this;
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: function(res) {
						console.log("条码类型：" + res.scanType);
						console.log("条码内容：" + res.result);
						_that.barCode = res.result;
						_that.confirm()
					},
				});
			},
			
			handleConfirm(item) {
				const that = this;
				uni.showModal({
					title: '出库确认',
					content: '是否确认出库？',
					confirmColor: '#00007f',
					success: (res) => {
						if (!res.confirm) {
							return false;
						} else {
							this.$u.api.ktnw.rdOrderConfirm({
								selIds: item.djno,
							}).then(res => {
								if (res.result == 'true') {
									this.$u.toast('成功');
									this.query = {
										pageNo: 1,
										pageSize: 20,
									};
									this.loadData();
								}else{
									this.$refs.jsError.showError('',res.message,'error');
								}
							});
						}
					}
				})
			},
		
			toForm(item){
				uni.$off('xwscan', this.BroadcastScanningToObtainData)
				uni.navigateTo({
					url: '/pages/ktnw/ckdd/form?djno=' + item.djno,
				})
			},
			reset() {
				this.list = [];
				this.query = {
					pageNo: 1,
					pageSize: 20,
				};
				this.confirm();
				this.show = false
			},
			submit() {
				this.list = [];
				this.query.pageNo = 1;
				this.confirm();
				this.show = false
			},
			startConfirm(e) {
				this.query.planArrDate_gte = e.year + '-' + e.month + '-' + e.day;
			},
			endConfirm(e) {
				this.query.planArrDate_lte = e.year + '-' + e.month + '-' + e.day;
			},
			customBack() {
				// 跳转到工作台页面
				// uni.navigateTo({
				//   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
				// });
				uni.navigateBack({
					delta: 1,
				});
			},
			async calculateScrollViewHeight() {
				try {
					this.headerHeight = 52
					// 计算tabBar高度
					if (this.flag) {
						this.tabBarHeight = 60; // 假设tabbar高度为50px，实际应根据实际情况获取
					} else {
						this.tabBarHeight = 0;
					}
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
				} catch (error) {
					console.error('Error while calculating ScrollView height:', error);
				}
			},

			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					// this.query.pageNo += 1;
					this.confirm();
				}, 100);
			},
			loadData(type) {
				// 循环10次重复赋值  needShListData
				this.$u.api.ktnw.rdOrderListData(this.query).then((res) => {
					if (res.list.length >= 0) {
						// this.xmList = res.list
						if (res.list.length < 20 || res.list.length == 0) {
							this.loadStatus = "nomore";
						}
						var data = res.list;
						if (type == "add") {
							for (var i = 0; i < data.length; i++) {
								this.list.push(data[i]);
							}
						} else {
							this.list = data;
						}
						// 加一个checked属性，用于标记是否选中
						for (var i = 0; i < data.length; i++) {
							data[i].checked = false;
						}
					}
				});
			},
			async refresherrefresh() {
				this.triggered = true;
				this.query.pageNo = 1;
				await this.confirm();
				const scrollTop = 0
				uni.pageScrollTo({
					scrollTop,
					duration: 0,
				});
				setTimeout(() => {
					this.triggered = false;
				}, 500);
			},
		},
	};
</script>
<style lang="scss" scoped>
	uni-checkbox::before {
		opacity: 0 !important;
	}
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
	
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
	
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	.text-border{
		border:2px solid  rgb(170, 170, 170); 
		border-radius: 5px;
		position: relative;
		padding-top: 20rpx;
		margin-top: 40rpx;
		padding-left: 20rpx;
		.text{
			position: absolute;
			background-color: #fff;
			padding: 10rpx 10rpx;
			top: -25rpx;
			right: 30rpx;
		}
	}
	.custom-style{
		// background-color: rgba(25, 190, 107, 0.7);
		
	}	
	.text-xxl{
		font-size:60rpx;
	}
	.cu-bar {
		min-height: 60px;
	}
	
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}
	
	.foot {
		background: #fff;
	}
	
	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}
	
	.title {
		width: 200rpx;
	}
	
	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}
	
	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}
	
	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	.footer {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		background: #fff;z-index: 999;
		border-top: 1px solid #eee;
	}
</style>